import { Component, useState, useEffect } from 'react';
import { View, Input, Video, Image } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { CopyToClipboard } from '@/utils/utils'
import './index.scss';
const RenderLink = (props) => {
  const { params } = getCurrentInstance().router
  const { url = '' } = params
  const [data, setData] = useState('')
  const getFileType = (url) => {
    const extension = url.split('.').pop().toLowerCase()

    if (extension === 'mp4' || extension === 'avi' || extension === 'mov') {
      return 'video'
    }

    if (extension === 'jpg' || extension === 'jpeg' || extension === 'png' || extension === 'gif') {
      return 'image'
    }

    if (extension === 'mp3' || extension === 'wav' || extension === 'ogg') {
      return 'audio'
    }

    if (extension === 'pdf') {
      return 'pdf'
    }
    if (extension === 'txt') {
      return 'txt'
    }

    return 'file'
  }
  const [type, setType] = useState(null)
  useEffect(() => {
    setType(getFileType(url))
  }, [])
  const fileOpen = () => {
    Taro.downloadFile({
      url: url,
      success: function (res) {
        var filePath = res.tempFilePath
        if (type === 'txt') {
          let fs = Taro.getFileSystemManager();
          const filePath = res.tempFilePath;
          fs.readFile({
            filePath: filePath,
            encoding: 'utf8',
            complete(res) {
              setData(res.data);
            }
          })
          return
        }
        Taro.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功！')
          },
          fail: () => {
            CopyToClipboard(url, '复制链接成功,请前往浏览器打开或下载')
          }
        })
      }
    })
  }
  const renderFunction = () => {
    if (type === 'video') {
      return <Video className='RenderLink_video' src={url}></Video>
      // 处理视频文件
    } else if (type === 'image') {
      // 处理图片文件
      return <Image mode='widthFix' className='RenderLink_image' src={url}></Image>
    } else if (type === 'audio') {
      return <Audio src={url} controls />
      // 处理音频文件
    } else {
      // 处理其他类型文件
      if (type) {
        fileOpen()
        return type === 'pdf' ? <View className='RenderLink_other' onClick={() => fileOpen()}>打开pdf文件</View> : <View>{data}</View>

      }
      return null
    }
  }
  return <View className='RenderLink_box'>
    {renderFunction()}
  </View>
}
export default RenderLink